<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
<p>
<form action="calc.php" method="get">
<input type="text" name="expr"><input type="submit" value="=" />
</form>

<?php 
$expr = $_GET["expr"];
if ($expr == '')
	return;
	
$num = '-?\d*\.?\d*';
$ops = '\+\-\*/';
	
if (preg_match('#([^\.\d'.$ops.'])#', $expr))
	$ret = 'Error: invalid characters';
else if (!preg_match('#^('.$num.')(['.$ops.']'.$num.')*$#', $expr))
	$ret = 'Error: invalid expression';
else if (preg_match('#/-?0+(['.$ops.']|$)#', $expr))
	$ret = 'Error: division by zero';
else if (preg_match('#(['.$ops.'][\+\*/])|\-\-#', $expr))
	$ret = 'Error: invalid operators';
else {
	eval("\$ret = $expr;");
}
echo $expr." = ".$ret;
?>

</p>
</body>
</html>

